package com.atguigu.common.valid;

import cn.hutool.core.util.ArrayUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;


/**
 * 自定义 JSR 303 注解进行校验
 * ConstraintValidator<K,T>
 *      K:JSR 注解
 *      T:校验数据类型为xxx
 */
public class ListValueConstraintValidator  implements ConstraintValidator<ListValue,Integer> {

    private Set<Integer> valueSet = new HashSet<>();

    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] values = constraintAnnotation.values();
        if (ArrayUtil.isNotEmpty(values)){
            for (int value : values) {
                valueSet.add(value);
            }
        }
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return valueSet.contains(value);
    }
}
